package deepbrain.simnetwork.structure;


/**
 * 
 * 
 * @author Li Yang
 * @create 2009-2-21
 */
public class MatrixUtils {

	public static final int STRING_BUILDER_INITIAL_SIZE = 200;

	public static boolean validateMatrix(double[][] matrix) {
		try {

			if (matrix == null)
				return false;

			int numOfRows = matrix.length;
			if (numOfRows == 0) // Allow Blank Matrix
				return true;

			int numOfCols = matrix[0].length;
			for (double[] row : matrix) {
				if (row.length != numOfCols)
					return false;
			}

			return true;

		} catch (Exception e) {
			return false;
		}
	}

	public static boolean validateMatrix(boolean[][] matrix) {
		try {

			if (matrix == null)
				return false;

			int numOfRows = matrix.length;
			if (numOfRows == 0) // Allow Blank Matrix
				return true;

			int numOfCols = matrix[0].length;
			for (boolean[] row : matrix) {
				if (row.length != numOfCols)
					return false;
			}

			return true;

		} catch (Exception e) {
			return false;
		}
	}

	public static boolean validateMatrix(int[][] matrix) {
		try {

			if (matrix == null)
				return false;

			int numOfRows = matrix.length;
			if (numOfRows == 0) // Allow Blank Matrix
				return true;

			int numOfCols = matrix[0].length;
			for (int[] row : matrix) {
				if (row.length != numOfCols)
					return false;
			}

			return true;

		} catch (Exception e) {
			return false;
		}
	}

	public static <T> boolean validateMatrix(T[][] matrix) {
		try {

			if (matrix == null)
				return false;

			int numOfRows = matrix.length;
			if (numOfRows == 0) // Allow Blank Matrix
				return true;

			int numOfCols = matrix[0].length;
			for (T[] row : matrix) {
				if (row.length != numOfCols)
					return false;
				for (T element : row) {
					if (element == null)
						return false;
				}
			}

			return true;

		} catch (Exception e) {
			return false;
		}
	}

	public static <T> String getMatrixAsString(Matrix<T> matrixType) {
		StringBuilder builder = new StringBuilder(STRING_BUILDER_INITIAL_SIZE);
		builder.append("\t");
		T[][] matrix = matrixType.matrix;
		int colNum = matrix[0].length;
		for (int i = 1; i <= colNum; i++) {
			builder.append(i);
			builder.append(":");
			builder.append("\t");
		}
		builder.append("\n");
		int rowNum = 0;
		for (T[] row : matrix) {
			rowNum++;
			builder.append("[");
			builder.append(rowNum);
			builder.append("]");
			builder.append("\t");
			for (T element : row) {
				builder.append(matrixType.serializeWeight(element));
				builder.append("\t");
			}
			builder.append("\n");
		}
		return builder.toString();
	}
	
	public static <T> Object[][] cloneMatrix(T[][] src,int numOfRows,int numOfCols) {
		Object[][] newMatrix = new Object[numOfRows][numOfCols];
		for (int row = 0; row < numOfCols; row++)
			System.arraycopy(src[row], 0, newMatrix[row], 0, numOfCols);
		return newMatrix;
	}
}
